package itbour.onetouchshow.activity.login;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.BootVideoPalyActivity;
import itbour.onetouchshow.activity.version1_3.MainActivityV3;
import itbour.onetouchshow.base.BaseApplication;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.observable.NetWorkObservable;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;

/**
 * Created by onetouch on 2017/11/25.
 */

public class SplashActivity extends MVPBaseActivity<SplashView, SplashPresenter> implements SplashView {

    public static String appId = "app_id=2018022402264996&biz_content=%7B%22body%22%3A%22%E4%BA%A4%E6%98%93%E6%8F%8F%E8%BF%B0%22%2C%22subject%22%3A%22%E4%B8%80%E9%94%AE%E7%A7%80%E6%B5%8B%E8%AF%95%E8%AE%A2%E5%8D%95%22%2C%22out_trade_no%22%3A%221523948378670%22%2C%22timeout_express%22%3A%221h%22%2C%22total_amount%22%3A%220.01%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22goods_type%22%3A%220%22%7D&charset=utf-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fwww.yijianxiu.com%2F&sign_type=RSA2&timestamp=2018-04-17%2014%3A59%3A38&version=1.0&sign=YzMruVu1%2BnDru9%2B83hOLkn%2Bp%2FOI27cI2lXxBfjEJGQuU0mdCCXvIUy4pMn5c3Lm4es7Iibows2hZSVvgO%2BsvgTMpE1iznyhojRSovq9zDF3ssq4Wzhi2DnTNaU2%2BwfwCN5fFhv39oJpeMEYpjcs16cRSpP6twEFNlUSzywqxMN%2FYGUlodQKwl58Khs5UKAAeW7sWlwpaPEWRxeaoHsYHrOi%2FSkYNN9h5ndC7kEC7iz6WFy0KAcpSlNWHgAapcpfMTIfOr0wHql9Hye2BIP%2Fze8jkxZoaFsf%2Bz7stAw%2Fb8w8NFKFm0jrYu9FRhc9vz4GdYhUDFwzLVF1MTCfgAWpJMA%3D%3D";
    //最大失败次数
    private final int MAX_FAIL_COUNT = 3;
    private boolean initAppBasicInfoSuccess;
    //请求已经失败过一次
    private boolean alreadyFail;
    private boolean isFirst;
    private Handler mHandler;
    //请求失败的次数
    private int failCount = 0;
    private Runnable getDataRunnable = new Runnable() {
        @Override
        public void run() {
            mPresenter.getHomeDetailsData();
        }
    };
    private NetWorkObservable.NetWorkObserver observer = new NetWorkObservable.NetWorkObserver() {
        @Override
        public void onNetWorkStatusChange(boolean b) {
            if (alreadyFail) {
                failCount = 0;
                mHandler.postDelayed(getDataRunnable, 2000);
            }
        }

        @Override
        public void onNewWorkEnvironment(NetWorkObservable.NetStateChangeEvent.NetState netState) {

        }
    };
    private Runnable intoAppRunnable = new Runnable() {
        @Override
        public void run() {
            if (initAppBasicInfoSuccess) {
                //获取基础信息成功则进入页面
                if (isFirst) {
                    openActivity(BootVideoPalyActivity.class);
                } else {
                    openActivity(MainActivityV3.class);
                }
                finish();
            } else {
                if (alreadyFail == false) {
                    //已经失败过
                    alreadyFail = true;
                }
                //获取基础信息失败 再次获取基础信息
                mHandler.postDelayed(getDataRunnable, 2000);
                failCount += 1;

            }
        }
    };

    @Override
    public void loadSucceed(String result) {
        if (SplashActivity.this != null) {
            initAppBasicInfoSuccess = true;
            if (alreadyFail) {
                UIUtils.getHandler().post(intoAppRunnable);
            }
        }
    }

    @Override
    public void loadFaild(String error) {
        if (SplashActivity.this != null) {
            initAppBasicInfoSuccess = false;
            if (alreadyFail) {
                if (failCount >= MAX_FAIL_COUNT) {
                    mHandler.removeCallbacks(getDataRunnable);
                    mHandler.removeCallbacks(intoAppRunnable);
                    T_.showCustomToast("网络异常,请检查网络");
                    return;
                }
                failCount += 1;
                mHandler.postDelayed(getDataRunnable, 2000);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        // videoWHDA();
        mHandler = new Handler();
        mPresenter.getHomeDetailsData();
        isFirst = SpUtils.getInstance().getBoolean("isFirst", true);
        SpUtils.getInstance().removeKey(AppConst.PLAY_MOVIE_KEY);
        hideBottomUIMenu();
        UIUtils.getHandler().postDelayed(intoAppRunnable, 2000);
        BaseApplication.instance().registerNetWorkObserver(observer);


//        Button button= findViewById(R.id.btn_pay);
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        PayInfo payInfo = new PayInfo();
//                        payInfo.setSign(appId);
//                        ThirdPayUtils.initialize(SplashActivity.this).pay(PayPlatform.AliPay, payInfo, new PayListener() {
//                            @Override
//                            public void paySuccess() {
//                                T_.showToastReal("支付成功");
//                            }
//
//                            @Override
//                            public void payFailure(Exception e) {
//                                T_.showToastReal("支付失败");
//                            }
//
//                            @Override
//                            public void userCancel() {
//
//                            }
//                        });
//                    }
//                });
//
//            }
//        });


    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onDestroy() {
        BaseApplication.instance().unregisterNetWorkObserver(observer);
        mHandler.removeCallbacks(intoAppRunnable);
        mHandler.removeCallbacks(getDataRunnable);
        super.onDestroy();
    }
}
